#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <semaphore.h>
#include <errno.h>

#include <stdlib.h>
#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>
#include <unistd.h>


#define SHM_KEY      (key_t)1097
#define SHM_PERM  (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)

int shMemSegID;

int shmFlags;

char * sharedMem;

/**
 * AQUI SETA A REGIÃO COMPARTILHADA DA MEMORIA, EU PENSEI QUE SÓ OS ASSENTOS SERVEM...
 */
void setUpSeats() {
    shmFlags = IPC_CREAT | SHM_PERM;

    if ((shMemSegID = shmget(SHM_KEY, 7 * sizeof (char), shmFlags)) < 0) {
        perror("SERVER: shmget");
        exit(EXIT_FAILURE);
    }

    shmFlags = 0;
    if ((sharedMem = shmat(shMemSegID, NULL, shmFlags)) == (void *) - 1) {
        perror("SERVER: shmat");
        exit(EXIT_FAILURE);
    }
}



/**
 * AQUI LIBERA A REGIÃO DOS ASSENTOS
 */
void tearDownSeats() {

    if (shmdt(seats) < 0) {
        perror("SERVER: shmdt");
        exit(EXIT_FAILURE);
    }

    if (shmctl(shMemSegID, IPC_RMID, NULL) < 0) {
        perror("SERVER: shmctl");
        exit(EXIT_FAILURE);
    }
}

/**
 * TUDO DEVE SER FEITO ENTRE AS CHAMAS DE setUpSeats E tearDownSeats
 * @param argc
 * @param argv
 * @return
 */
int main(int argc, char** argv) {

    setUpSeats();

    if ((seats_sem = sem_open("/boat.sem", O_CREAT | O_EXCL, S_IRWXU | S_IRWXO, 0)) == SEM_FAILED) {
        fprintf(stderr, "Boat sem could not be opened!\n");
    }

    sem_wait(seats_sem);

    fprintf(stderr, "%s\n", seats);

    tearDownSeats();

    return (EXIT_SUCCESS);
}
